package com.canomo.base.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.canomo.base.dao.FileInfoDao;
import com.canomo.base.entity.FileInfo;
import com.canomo.base.service.FileInfoService;
import com.canomo.constants.FileConstants;
import com.canomo.modules.sys.dao.RoleDao;
import com.canomo.utils.ConfigUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 记录文件信息表 服务实现类
 * </p>
 *
 * @author xiaoj
 * @since 2018-07-15
 */
@Service
public class FileInfoServiceImpl extends ServiceImpl<FileInfoDao, FileInfo> implements FileInfoService {

    @Override
    public Long save(File file) {
        return null;
    }

    @Override
    public Long save(MultipartFile file) {
        try {
            //获得文件的MD5校验码
            byte[] md5 = DigestUtils.md5Digest(file.getInputStream());
            String md5Str = DigestUtils.md5DigestAsHex(md5);
            //根据MD5码查询文件是否已经保存过
            FileInfo fileInfo = new FileInfo();
            fileInfo.setFileMd5(md5Str);
            FileInfo newFileInfo = baseMapper.selectOne(fileInfo);
            if (newFileInfo == null) {
                //表示不存在，之前没有保存过该文件
                fileInfo.setFileName(StringUtils.substringBeforeLast(file.getOriginalFilename(),"."));
                fileInfo.setFileSize(file.getSize());
                fileInfo.setFileType(file.getContentType());
                fileInfo.setFilePath(buildFilePath(file));
                baseMapper.insert(fileInfo);
                System.out.println(fileInfo.getId());
                return fileInfo.getId();
            } else {
                //如果存在的话，则取出文件路径
                String filePath = newFileInfo.getFilePath();
                if (!new File(filePath).exists()) {
                    //物理文件不存在,则重新拷贝一份重新保存到物理文件路径下
                    FileUtils.copyToFile(file.getInputStream(),new File(filePath));
                }
                return newFileInfo.getId();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成文件路径,同时保存文件
     * @param file
     * @return
     */
    private String buildFilePath(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = StringUtils.substringAfterLast(originalFilename,".");
        //根据文件后缀，找到文件存储对应的文件类型
        //比较图片的存储在images下面
        String convertPath  = FileConstants.CONVERT_PATH.getOrDefault(suffix,FileConstants.CONVERT_PATH_OTHER);
        String newFileName = StringUtils.replaceAll(UUID.randomUUID().toString(),"-","") + "." + suffix;
        String rootPath = ConfigUtils.get(FileConstants.FILE_ROOT_PATH);
        //根据当前的年月日和小时生成路径
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        String pathDir = rootPath + File.separator + convertPath
                + File.separator + calendar.get(Calendar.YEAR)
                + File.separator + (calendar.get(Calendar.MONTH) + 1)
                + File.separator + calendar.get(Calendar.DAY_OF_MONTH)
                + File.separator + calendar.get(Calendar.HOUR_OF_DAY);
        File pathFile = new File(pathDir);
        if (!pathFile.exists()) {
            boolean flag = pathFile.mkdirs();
            if (!flag) {
                return null;
            }
        }
        try {
            FileUtils.copyToFile(file.getInputStream(),new File(pathDir + File.separator + newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pathDir + File.separator + newFileName;
    }

    public static void main(String[] args) {
        System.out.println(FileConstants.CONVERT_PATH.getOrDefault("jpga","other"));
    }

}
